<template>
  <GlobalBG title="处置详情" :showBack="true" :showCollege="false">
    <view class="event-detail-container">
      <!-- 事件信息头部 -->
      <view class="header-section">
        <view class="header-content">
          <text class="header-title">{{ incident.eventCodeDesc || '--' }}</text>
        </view>
        <view
          class="status-badge"
          :class="`status-badge-${getStatusTagColor(incident.eventStatus)}`"
          >{{ incident.eventStatusValue || '--' }}</view
        >
        <view class="info-section">
          <text class="info-item">时间：{{ incident.eventTime || '--' }}</text>
          <text class="info-item">地点：{{ incident.address || '--' }}</text>
          <text class="info-item">社区：{{ incident.orgName || '--' }}</text>
        </view>
        <view class="tag-section">
          <text
            class="tag"
            :class="`tag-${getStatusTagColor(incident.eventClass)}`"
            >{{ incident.eventClassDesc }}</text
          >
          <text
            class="tag"
            :class="`tag-${getStatusTagColor(incident.eventSource)}`"
            >{{ incident.eventSourceDesc }}</text
          >
        </view>
      </view>

      <!-- 事件描述区域 -->
      <view class="description-section">
        <text class="title">事件描述</text>
        <text class="description-text">{{ incident.eventCodeDesc }}</text>
        <view class="image-preview">
          <image
            v-for="(image, index) in incident.images"
            :key="index"
            :src="image"
            class="preview-image"
            @click="openModal(image)"
          />
        </view>
      </view>

      <!-- 处理流程区域 -->
      <view class="process-section">
        <text class="title">处理流程</text>
        <view class="process-item">
          <text class="process-step" :style="getProcessStepStyle(1)">1</text>
          <view class="process-content">
            <text class="sub-title">研判</text>
            <text class="info"
              >研判人员: {{ incident.judgementMemberName || '--' }}</text
            >
            <text class="info"
              >研判时间: {{ incident.judgementDatetime || '--' }}</text
            >
            <text class="info"
              >研判结果: {{ incident.judgementResult || '--' }}</text
            >
          </view>
        </view>
        <view class="process-item">
          <text class="process-step" :style="getProcessStepStyle(2)">2</text>
          <view class="process-content">
            <text class="sub-title">分派</text>
            <text class="info"
              >分派人: {{ incident.assignMemberName || '--' }}</text
            >
            <text class="info"
              >分派时间: {{ incident.assignTime || '--' }}</text
            >
            <text class="info"
              >负责人: {{ incident.assignedMemberName || '--' }}</text
            >
          </view>
        </view>
        <view class="process-item">
          <text class="process-step" :style="getProcessStepStyle(3)">3</text>
          <view class="process-content" v-if="incident.eventStatus != '10'">
            <text class="sub-title">处置</text>
            <text class="info"
              >处置状态: {{ incident.eventStatusValue || '--' }}</text
            >
            <text class="info"
              >驱离记录: {{ incident.handlerTime || '--' }}</text
            >
            <text class="info"
              >驱离次数: {{ incident.handlerTimes || '--' }}</text
            >
            <text class="info">驱离人员: {{ incident.person || '--' }}</text>
            <text class="info"
              >处置人: {{ incident.assignedMemberName || '--' }}</text
            >
            <text class="info"
              >处置时间: {{ incident.handlerTime || '--' }}</text
            >
            <text class="info"
              >处置详情: {{ incident.handlerRemark || '--' }}</text
            >
            <view class="image-preview">
              <image
                v-for="(image, index) in incident.handlerPicL"
                :key="index"
                :src="image"
                class="preview-image"
                @click="openModal(image)"
              />
            </view>
          </view>
          <view class="process-content" v-else>
            <text class="sub-title">待处置</text>
          </view>
        </view>
      </view>

      <!-- 事件处置区域 -->
      <view class="disposition-section" v-if="incident.eventStatus === '10'">
        <text class="title">事件处置</text>
        <view class="input-container">
          <textarea
            class="disposition-input"
            placeholder="请输入描述"
            v-model="dispositionDescription"
          />
        </view>
        <text class="image-upload-title">图片上传</text>
        <view class="image-upload-preview">
          <image
            v-for="(item, index) in uploadedImages"
            :key="index"
            :src="item"
            class="preview-image"
            @click="openModal(item)"
          />
        </view>
        <view
          class="upload-button"
          v-if="uploadedImages.length < 3"
          @click="handleImagePicker"
        >
          <text class="plus-icon">+</text>
        </view>
        <view class="limit-text">最多可上传3张图片，支持jpg、png等格式</view>
        <button class="submit-button" @click="handleSubmit">确认提交</button>
      </view>
      <!-- 引入模态框组件 -->
      <modal-image
        :visible="modalVisible"
        :imageSrc="selectedImage"
        @update:visible="modalVisible = $event"
      />
    </view>
  </GlobalBG>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import ModalImage from '../../components/ModalImage.vue';
import api from '@/api/modules/event';
import { onLoad } from '@dcloudio/uni-app';

const incident = reactive({
  busizEventId: '',
  eventCodeDesc: '',
  eventTime: '',
  address: '',
  orgName: '',
  eventStatusValue: '',
  eventStatus: '', // 事件状态
  images: [] as string[],
  eventClass: '', // 事件类别code
  eventClassDisplay: '', //时间类别文字
  eventSource: '', // 事件来源code
  eventSourceDisplay: '', // 事件来源文字
  judgementMemberName: '', //研判人员
  judgementDatetime: '', //研判时间
  judgementResult: '', //研判结果
  assignMemberName: '', //分派人
  assignTime: '', //分派时间
  assignedMemberName: '', //处置人
  handlerTime: '', //处置时间+驱离记录
  handlerTimes: '', //驱离次数
  person: '', //处置人员
  handlerRemark: '', //处置详情
  handlerPicL: [], //处置图片
});

const dispositionDescription = ref('');
const uploadedImages = ref<string[]>([]);
const modalVisible = ref(false);
const selectedImage = ref('');

// 初始化时调用接口获取数据
onLoad((options) => {
  console.log('页面加载时调用接口获取数据', options);
  const busizEventId = options.busizEventId; // 兼容两种可能的参数名
  if (busizEventId) {
    fetchIncidentDetail(busizEventId);
  } else {
    uni.showToast({
      title: '缺少事件ID参数',
      icon: 'none',
    });
    uni.navigateBack();
  }
});

const fetchIncidentDetail = async (id: string) => {
  try {
    const res = await api.getEventDetail({ busizEventId: id });
    console.log('获取事件详情成功:', res);
    if (res.data) {
      Object.assign(incident, {
        busizEventId: res.data.busizEventId,
        eventStatusValue: res.data.eventStatusValue,
        eventTime: res.data.eventTime,
        eventStatus: res.data.eventStatus, //code
        eventStatusValue: res.data.eventStatusValue,
        address: res.data.address, // 使用第一个事件的地址
        orgName: res.data.orgName, // 使用第一个事件的社区名
        eventCodeDesc: res.data.eventCodeDesc, // 使用第一个事件的描述+标题
        eventClass: res.data.eventClass, // 事件类别
        eventClassDesc: res.data.eventClassDesc, // 事件类别
        eventSource: res.data.eventSource, // 事件来源
        eventSourceDesc: res.data.eventSourceDesc, // 事件来源
        images: [res.data.pic] || [], // 使用接口返回的图片URL
        judgementMemberName: res.data.judgementMemberName,
        judgementDatetime: res.data.judgementDatetime,
        judgementResult: res.data.judgementResult,
        assignMemberName: res.data.assignMemberName,
        assignTime: res.data.assignTime,
        assignedMemberName: res.data.assignedMemberName,
        handlerTime: res.data.handlerTime,
        handlerTimes: res.data.handlerTimes,
        person: res.data.person,
        handlerRemark: res.data.handlerRemark,
        handlerPicL: res.data.handlerPicL,
      });
    } else {
      throw new Error(res.message || '获取详情失败');
    }
  } catch (error) {
    console.error('获取事件详情失败:', error);
    uni.showToast({
      title: '获取详情失败',
      icon: 'none',
    });
  }
};

// 上传图片的方法
const handleImagePicker = async () => {
  try {
    const result = await uni.chooseImage({
      count: 3 - uploadedImages.value.length,
      sizeType: ['compressed'], // 只用压缩图
      sourceType: ['album', 'camera'],
    });

    if (result.tempFilePaths && result.tempFiles) {
      for (let i = 0; i < result.tempFilePaths.length; i++) {
        const filePath = result.tempFilePaths[i];
        const file = result.tempFiles[i];

        if (beforeUpload(file)) {
          await customUpload(filePath);
        }
      }
    }
  } catch (error) {
    console.error('选择图片失败:', error);
  }
};

// 上传图片前的检查
const beforeUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt500K = file.size / 1024 < 500; // 500KB
  if (!isJPG) {
    uni.showToast({
      title: '上传图片只能是 JPG 或 PNG 格式!',
      icon: 'none',
    });
  }
  if (!isLt500K) {
    uni.showToast({
      title: '上传图片大小不能超过 500KB!',
      icon: 'none',
    });
  }
  return isJPG && isLt500K;
};

const customUpload = async (filePath: string) => {
  try {
    // 使用 uni.uploadFile API (Uni-app 官方推荐)
    const uploadResult = await new Promise<UniApp.UploadFileSuccess>(
      (resolve, reject) => {
        uni.uploadFile({
          url: '/integrated-workbench/v1/enforcement/picupload',
          filePath: filePath,
          name: 'file',
          header: {
            Authorization: 'Bearer your_token_here', // 如果需要token
          },
          success: (res) => {
            if (res.statusCode === 200) {
              try {
                const data = JSON.parse(res.data);
                resolve(data);
              } catch (e) {
                reject(new Error('解析响应数据失败'));
              }
            } else {
              reject(new Error(`上传失败: ${res.statusCode}`));
            }
          },
          fail: (err) => reject(err),
        });
      }
    );
    // 给images数组添加图片URL
    if (uploadResult.data && uploadResult.data.picPath) {
      uploadedImages.value.push(uploadResult.data.picPath);
      uni.showToast({ title: '上传成功', icon: 'success' });
    } else {
      throw new Error(uploadResult.message || '上传失败');
    }
  } catch (error) {
    console.error('上传失败:', error);
    uni.showToast({
      title: '上传失败: ' + (error.message || '未知错误'),
      icon: 'none',
    });
  }
};
// 确认提交
const handleSubmit = async () => {
  console.log('提交处置信息', {
    description: dispositionDescription.value,
    images: uploadedImages.value,
  });
  const obj = {
    busizEventId: incident.busizEventId,
    handleRemark: dispositionDescription.value,
    handlePicURL: uploadedImages.value.join(','),
  };
  try {
    const res = await api.confirmhandle(obj);

    console.log('提交成功:', res);
    uni.showToast({
      title: '提交成功',
      icon: 'success',
    });

    // 提交成功后返回上一页
    uni.navigateBack();
  } catch (err) {
    console.error('提交失败:', err);
    uni.showToast({
      title: '提交失败: ' + (err.message || '未知错误'),
      icon: 'none',
    });
  }
};

// 打开模态框并设置要显示的图片 URL
const openModal = (image: string) => {
  selectedImage.value = image;
  modalVisible.value = true;
};

// eventStatus  99完成 10处置  0指派
// 动态获取 process-step 的样式
const getProcessStepStyle = (step: number) => {
  const waitImageUrl = '/static/images/wait.png';
  const roundImageUrl = '/static/images/round.png';
  const completeImageUrl = '/static/images/wancheng.png';
  if (step === 3) {
    if (incident.eventStatus === '99') {
      return `background-image: url(${completeImageUrl}); background-size: cover;`;
    } else if (incident.eventStatus === '10') {
      return `background-image: url(${waitImageUrl}); background-size: cover;`;
    }
  }
  return `background-image: url(${roundImageUrl}); background-size: cover;`;
};

// 定义颜色映射函数
const getStatusTagColor = (statusCode: string): string => {
  switch (statusCode) {
    case '301':
      return 'urgent';
    case '101':
      return 'normal';
    case '201':
      return 'important';
    // 事件
    case '200':
      return 'intelligence';
    case '100':
      return 'artificial';
    case '110':
      return 'patrol';
    // 状态
    case '99':
      return 'wc';
    case '10':
      return 'cz';
    case '0':
      return 'zp';
    default:
      return 'normal';
  }
};
</script>

<style lang="scss" scoped>
/* 整体容器 */
.event-detail-container {
  padding: 20rpx;
  width: 100%;
  max-width: 750rpx; /* 适配750px宽 */
  margin: 0 auto;
  background: #f9f9f9;
}

/* 事件信息头部 */
.header-section {
  background: #ffffff;
  padding: 20rpx 30rpx;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  box-shadow: 0px 4px 16px rgba(0, 0, 0, 0.05);
  position: relative; /* 确保子元素 absolute 定位时的参考容器 */
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  position: relative;
}

.header-title {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
}

.status-badge {
  position: absolute;
  top: 0;
  right: 20rpx;
  display: inline-block;
  padding: 4rpx 10rpx;
  border-radius: 0rpx 0rpx 8rpx 8rpx;
  font-size: 24rpx;
  white-space: nowrap;
  &-wc {
    background: #c5f1e6;
    color: #39aa92;
  }
  &-cz {
    background: #ffe9d2;
    color: #ff982b;
  }
  &-zp {
    background: #e2e1ff;
    color: #9053ff;
  }
}

.info-section {
  font-size: 26rpx;
  color: #666;
}

.info-item {
  display: block;
  margin-bottom: 10rpx;
}

.tag-section {
  display: flex;
  gap: 10rpx;
  margin-top: 20rpx;
}

.tag {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 4rpx 10rpx;
  border-radius: 8rpx;
  font-size: 24rpx;
  color: #fff;
  white-space: nowrap;
  &-urgent {
    background: #ffe6e6;
    color: #ff2121;
  }
  &-normal {
    background: #d2f0ff;
    color: #45aff7;
  }
  &-important {
    background: #ffe9d2;
    color: #ff982b;
  }
  &-intelligence {
    background: #c5f1e6;
    color: #39aa92;
  }
  &-artificial {
    background: #d2f0ff;
    color: #45aff7;
  }
  &-patrol {
    background: #e2e1ff;
    color: #9053ff;
  }
}

/* 事件描述区域 */
.description-section {
  display: flex;
  flex-direction: column;
  background: #ffffff;
  padding: 20rpx 30rpx;
  border-radius: 16rpx;
  margin-top: 20rpx;
  box-shadow: 0px 4px 16px rgba(0, 0, 0, 0.05);
}

.title {
  font-size: 30rpx;
  font-weight: 500;
  margin-bottom: 10rpx;
}

.description-text {
  font-size: 26rpx;
  color: #666;
  margin-top: 10rpx;
}

.image-preview {
  display: flex;
  gap: 10rpx;
  margin-top: 10rpx;
}

.preview-image {
  width: 200rpx;
  height: 125rpx;
  border-radius: 12rpx;
  object-fit: cover;
  // background: #047aff;
}

/* 处理流程区域 */
.process-section {
  background: #ffffff;
  padding: 20rpx 30rpx;
  border-radius: 16rpx;
  margin-top: 20rpx;
  box-shadow: 0px 4px 16px rgba(0, 0, 0, 0.05);
}

.process-item {
  position: relative; /* 为伪元素定位 */
  margin: 20rpx 0;
  display: flex; /* 确保内容是 flex 布局，方便高度自动调整 */
  align-items: flex-start; /* 确保内容从顶部对齐 */
}

.process-step {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 38rpx;
  height: 38rpx;
  border-radius: 50%;
  font-weight: 500;
  font-size: 27rpx;
  color: #2263bf;
  line-height: 38rpx;
  letter-spacing: 1px;
  background-size: cover;
}

.process-step::after {
  content: '';
  display: block;
  position: absolute;
  bottom: 0;
  left: 18rpx; /* 调整线条位置，确保线条居中 */
  width: 2rpx;
  height: calc(
    100% - 50rpx
  ); /* 减去 process-step 的高度，确保线条不覆盖进 circle */
  background-color: #2263bf;
}

.process-item:last-child .process-step::after {
  display: none; /* 最后一项的线条要隐藏 */
}

.sub-title {
  font-size: 28rpx;
  font-weight: 500;
  color: #047aff;
  margin-bottom: 10rpx;
}

.info {
  font-size: 24rpx;
  color: #666;
  line-height: 1.5; /* 调整行高，确保与原型图一致 */
}

.process-content {
  display: flex;
  flex-direction: column;
  margin-left: 30rpx; /* 增加左侧固定间距 */
  align-items: flex-start; /* 确保内容从顶部对齐 */
}

/* 事件处置区域 */
.disposition-section {
  background: #ffffff;
  padding: 20rpx 30rpx;
  border-radius: 16rpx;
  margin-top: 20rpx;
  box-shadow: 0px 4px 16px rgba(0, 0, 0, 0.05);
}

.disposition-input {
  width: 100%;
  height: 200rpx;
  border: 2rpx solid #eaeaea;
  border-radius: 8rpx;
  font-size: 26rpx;
  padding: 20rpx;
  box-sizing: border-box;
}

.input-container {
  position: relative;
  margin-top: 20rpx;
}

.image-upload-title {
  font-size: 28rpx;
  font-weight: 500;
}

.image-upload-preview {
  display: flex;
  gap: 10rpx;
  margin-top: 20rpx;
}

.preview-image {
  width: 160rpx;
  height: 120rpx;
  object-fit: cover;
  border: 1rpx solid #eaeaea;
}

.upload-button {
  width: 160rpx;
  height: 120rpx;
  background: #f2f2f2;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8rpx;
  font-size: 80rpx;
  color: #999;
}

.limit-text {
  font-size: 24rpx;
  color: #666;
  margin-top: 20rpx;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  font-size: 23rpx;
  color: #999999;
  line-height: 33rpx;
  letter-spacing: 1px;
  text-align: left;
  font-style: normal;
}

.submit-button {
  width: 100%;
  height: 80rpx;
  background: #047aff;
  color: #fff;
  font-size: 28rpx;
  border-radius: 12rpx;
  margin-top: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
